// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {

	async guestlistAction(){

		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let lv = page.lv;
		let shopid = this.shop_userinfo.departmentid;

		let lvstr = '';
		if (lv !== '') {
			lvstr = ' AND g.level = '+lv;
		}

		let list = await this.model().query('SELECT g.*,v.vipname,IFNULL(c.count,0) AS count FROM `think_or_guest` AS g LEFT JOIN `think_or_guest_vipgrade` AS v ON v.id = g.`level` LEFT JOIN (SELECT 	COUNT(a.id) AS count, a.gid	FROM `think_or_guest` AS s LEFT JOIN `think_or_allotuser` AS a ON a.gid = s.id WHERE s.departmentid = '+shopid+' GROUP BY s.id) AS c ON c.gid = g.id WHERE g.departmentid = '+shopid+' AND ((g.name LIKE "%'+search+'%") OR (g.phone LIKE "%'+search+'%") OR (g.vipcard LIKE "%'+search+'%"))'+lvstr+' ORDER BY g.id DESC LIMIT '+(pages-1)*limits+','+limits+'');

		let counts = await this.model().query('SELECT count(g.id) as num FROM `think_or_guest` AS g WHERE g.departmentid = '+shopid+' AND ((g.name LIKE "%'+search+'%") OR (g.phone LIKE "%'+search+'%") OR (g.vipcard LIKE "%'+search+'%"))'+lvstr+'');

		let data = {
			data: list,
			count: counts[0].num
		}

		return this.json(data);
	}
	
	async addguestAction(){
		let ginfo = this.post();
		let shopid = this.shop_userinfo.departmentid;
		let time = Math.round(new Date().valueOf()/1000);

		let orid = await this.model('or_department').where({id: shopid}).getField('pid', true);

		let shoplist = await this.model('or_department')
				.alias('s')
				.join('`think_or_department` d on d.id=s.pid')
				.where({'s.pid': orid})
				.getField('s.id');

		if (ginfo.id*1) {
			let jgid = await this.model('or_department').where({id: shopid}).find()

			let chongfu = await this.model('or_guest')
					.alias('g')
					.join('`think_or_department` d on g.departmentid = d.id')
					.where({'g.phone':ginfo.phone, 'd.orcode': jgid.orcode, 'g.id':['!=',ginfo.id]})
					.find()

			let viprepeat = await this.model('or_guest').where({departmentid: ['IN', shoplist], vipcard: ginfo.vipcard, id:['!=',ginfo.id]}).select();

			if (!think.isEmpty(viprepeat)) {
				return this.fail('更改的会员卡号在连锁里重复');
			}

			if (!think.isEmpty(chongfu)) {
				return this.fail('该手机号已被使用！');
			}

			// 客户昵称
			let ggnamelen = ginfo.name.replace(/[\u0391-\uFFE5]/g, 'aa').length;

			if (ggnamelen > 7) {
				let namefirst = ginfo.name.substring(0,2);
				ginfo.nickname = ginfo.sex*1? namefirst+'先生':namefirst+'女士';
			} else {
				let namefirst = ginfo.name.substring(0,1);
				ginfo.nickname = ginfo.sex*1? namefirst+'先生':namefirst+'女士';
			}

			let gengxin = await this.model('or_guest').update(ginfo);
			return gengxin?this.success('更改成功'):this.fail('更改失败');
		}

		// 判断重复性（机构唯一）标准#010
		let or = await this.model('or_department').where({id: shopid}).find()

		let is_exist = await this.model('or_guest')
				.alias('g')
				.join('left join `think_or_department` d on g.departmentid = d.id')
				.where({'g.phone':ginfo.phone, orcode: or.orcode})
				.find()

		if (!think.isEmpty(is_exist)) {
			return this.fail('该手机号已被使用！');
		}

		let is_repeat = await this.model('or_guest').where({departmentid: ['IN', shoplist], vipcard: ginfo.vipcard}).select();
		
		if (!think.isEmpty(is_repeat)) {
			return this.fail('新增的客户会员卡号在连锁里重复');
		}

		let addone = {
			departmentid: shopid,
			username: ginfo.phone,
			name: ginfo.name,
			sex: ginfo.sex,
			phone: ginfo.phone,
			initial_info: ginfo.initial_info,
			password: think.md5(ginfo.phone),
			addtime: time,
			arrivetime: time,
			level: 1,
			vipcard: ginfo.vipcard,
			remarks: ginfo.remarks,
		}

		// 获取部门VIP张数
		let cardnum = await this.model('or_organizationcardnum').where({departmentid:or.pid}).find();
		//如果没有初始化并赋值
		let cardup = think.isEmpty(cardnum)?1:cardnum.cardnum+1;
		// data.vipcard = or.orcode + ''+cardup;

		//做更新操作
		if (think.isEmpty(cardnum)) {
			let res = await this.model('or_organizationcardnum').add({departmentid:or.pid,cardnum:1});
		}else{
			let res = await this.model('or_organizationcardnum')
			.where({departmentid:or.pid})
			.update({departmentid:or.pid,cardnum:cardup});
		}

		// 客户昵称
		let namelen = ginfo.name.replace(/[\u0391-\uFFE5]/g, 'aa').length;

		if (namelen > 7) {
			let namefirst = ginfo.name.substring(0,2);
			addone.nickname = ginfo.sex*1? namefirst+'先生':namefirst+'女士';
		} else if (namelen < 7) {
			let namefirst = ginfo.name.substring(0,1);
			addone.nickname = ginfo.sex*1? namefirst+'先生':namefirst+'女士';
		}

		let res = await this.model('or_guest').add(addone);
		return res?this.success("添加成功！"):this.fail('添加失败！');	
	}
	
	async editguestAction(){

		let data = this.post();
		data.username = data.phone;
		data.password = think.md5(data.phone);

		// 客户昵称
		let namelen = data.name.replace(/[\u0391-\uFFE5]/g, 'aa').length;
		if (namelen > 7) {
			let namefirst = data.name.substring(0,2);
			data['nickname'] = 1 == data.sex? namefirst+'先生':namefirst+'女士';
		} else if (namelen < 7) {
			let namefirst = data.name.substring(0,1);
			data['nickname'] = 1 == data.sex? namefirst+'先生':namefirst+'女士';
		}

		// 同机构下
		let orcode = await this.model('or_guest')
		.alias('g')
		.join('left join `think_or_department` d on g.departmentid = d.id')
		.where({'g.id': data.id})
		.getField('d.orcode', true)

		let is_exist = await this.model('or_guest')
		.alias('g')
		.join('left join `think_or_department` d on g.departmentid = d.id')
		.where({'g.phone':data.phone, orcode: orcode, 'g.id':['!=',data.id]})
		.find()

		//判断手机号是否重复
		if (!think.isEmpty(is_exist)) {
			return this.fail('该手机号已被使用！');
		}

		let res = await this.model('or_guest').update(data);
		return res?this.success("编辑成功！"):this.fail('编辑失败！');
	}

	//补位函数
	numfull(num,n){
		num = '00000000000000000'+num;
		return num.substring(num.length-n,num.length);
	}

	async getallgroupsAction(){
		let gid = this.get('gid');

		let shopid = this.shop_userinfo.departmentid;

		/*
		 * 1、分配员工，可以分配店下面的
		 * 2、可以分配部门下面的
		 * 3、可以分配小组下面的
		 */
		let shop = await this.model('or_department').where({id: shopid,isdisable:0}).find();

		let bumens = await this.model('or_department').where({pid: shopid,isdisable:0}).select();

		let groups = await this.model().query('SELECT xz.* FROM `think_or_department` AS xz LEFT JOIN `think_or_department` AS bm ON xz.pid = bm.id WHERE bm.pid = '+shopid+' AND bm.isdisable = 0 AND xz.isdisable = 0');

		let users = await this.model('or_app_user')
				.alias('u')
				.field('u.id, u.name as uname, p.name as pname, a.gid as gid, u.departmentid')
				.join('`think_or_allotuser` a on a.uid=u.id and a.gid='+gid)
				.join('`think_or_position` p on u.zhichengid=p.id')
				.where({'u.shopid': shopid, 'u.isdisable': 0})
				.select();

		let data = {
			shop: shop,
			bumens: bumens,
			groups: groups,
			users: users
		}

		return this.json(data);
	}
	
	// 插入和读取员工分配的数据
	async allotguestAction(){

		let data = JSON.parse(this.post('data'));

		/*
		 * 现在的方法：先把之前分配的全部删除，然后再重新添加
		 * 还有一种方法：找到分配相同的，然后删除不同的，再把没有的添加上去
		 */

		let model = this.model('or_allotuser');

		await model.transaction(async ()=>{
		 	try {

		 		let existGids = await model.where({gid: data.gid}).select();

		 		if (!think.isEmpty(existGids)) {
		 			let delGids = await model.where({gid: data.gid}).delete();
		 			if (!delGids) {
		 				await model.rollback();
		 				return this.fail('重新分配失败')
		 			}
		 		}

		 		if (!think.isEmpty(data.many)) {
		 			let addMany = await model.addMany(data.many);
		 			if (!addMany) {
		 				await model.rollback();
		 				return this.fail('重新分配失败')
		 			}
		 		}

	 			await model.commit();
	 			return this.success('重新分配员工成功');

		 	} catch (e) {
		 		console.log(e)
		 		await model.rollback();
		 		return this.fail('重新分配失败');
		 	}
		})
	}

	// 客户停用和启用的状态(如果客户有VIP卡则不能操作)
	async gueststatusAction(){
		let id = this.post('id');
		let status = this.post('status');
		let whetherVip = await this.model('or_shop_guestcard').where({guestid:id,status:1}).select();
		if (!think.isEmpty(whetherVip)) {
			return this.fail('不能操作该客户！');
		}
		if (status) {
			let model = this.model('or_guest');
			await model.transaction(async () => {
				try{
					let res = await model.where({id:id}).update({isdisable:status});
					let isFenpei = await this.model('or_allotuser').db(model.db()).where({gid:id}).select();
					let delfenpei = 1;
					if (!think.isEmpty(isFenpei)) {
						delfenpei = await this.model('or_allotuser').db(model.db()).where({gid:id}).delete();
					}
					if (res && delfenpei) {
						await model.commit();
						return this.success('弃用成功');
					} else {
						await model.rollback();
						return this.fail('弃用失败');
					}
				}catch(e){
					await model.rollback();
					return this.fail('弃用失败');
				}
			})
		} else {
			let res = await this.model('or_guest').where({id:id}).update({isdisable:status});
			return res?this.success('启用成功'):this.fail('启用失败');
		}
	}

	// 获取客户起初未审核卡项和产品信息
	async queryinitailAction(){
		let id = this.get('gid');

		let shopid = this.shop_userinfo.departmentid;

		let currentTime = Math.round(new Date().valueOf()/1000);

		let orid = await this.model('or_department').where({id: shopid}).getField('pid', true);

		// 客户基本信息
		let ginfo = await this.model('or_guest').where({id: id}).find();

		if (ginfo.initial_info) {
			return this.fail('客户起初状态已审核');
		}

		let slist = await this.model('or_shop_guestcardsubject')
				.alias('gs')
				.field('gs.*, s.name, s.number')
				.join('`think_or_subject` s on s.id=gs.subjectid')
				.where('gs.shopid='+shopid+' AND gs.guestid='+id+' AND (gs.endtime>'+currentTime+ ' OR gs.nownum>0 ) AND gs.isdisabled=0')
				.select();

		let glist = await this.model('or_shop_guest_temp_reserve')
				.alias('t')
				.field('t.*, g.name as gname, g.number')
				.join('`think_or_goods` g on g.id=t.goodsid')
				.where('t.guestid='+id+' AND t.shopid='+shopid+' AND t.nownum > 0 AND t.isdisabled=0')
				.select();

		let vlist = await this.model().query('select * from `think_or_guest_vipgrade` where departmentid='+orid+' or departmentid=0');

		let data = {
			ginfo: ginfo,
			slist: slist,
			glist: glist,
			vlist: vlist
		}

		return this.json(data);
	}

	// 自动根据会员卡的ID获取对应的项目列表
	async autogetsubjectsAction(){
		let id = this.get('id');

		let subjects = await this.model('or_cardsubject')
				.alias('cs')
				.field('s.id,s.name, s.remarks, s.usetime, cs.num, cs.price')
				.join('think_or_subject s on s.id = cs.subjectid')
				.where({'cs.cardid':id})
				.select();

		return this.json(subjects);
	}

	// 设置客户起初信息
	async setguestinitialAction(){

		let data = JSON.parse(this.post('data'));

		let ginfo = data.ginfo, slist = data.slist, glist = data.glist, delsid = data.delsid, delgid = data.delgid;

		// 判断当前客户起初是否已经审核
		let isin = await this.model('or_guest').where({id: ginfo.id}).find();

		if (isin.initial_info) {
			return this.fail('当前顾客起初已审核，不能修改！');
		}

		let shopid = this.shop_userinfo.departmentid;

		let addtime = Math.round(new Date().valueOf()/1000);

		let model = this.model('or_guest');

		await model.transaction(async ()=>{

			try {

				if (delsid.length) {
					let delSubsRes = await this.model('or_shop_guestcardsubject').db(model.db()).where({id: ['IN', delsid]}).delete();
					if (!delSubsRes) {
						await model.rollback();
						return this.fail('删除卡项失败');
					}
				}

				if (delgid.length) {
					let delGodsRes = await this.model('or_shop_guest_temp_reserve').db(model.db()).where({id: ['IN', delgid]}).delete();
					if (!delGodsRes) {
						await model.rollback();
						return this.fail('删除产品失败');
					}
				}

				if (slist.length) {
					let gengSubs = [], addSubs = [];

					for (var i = slist.length - 1; i >= 0; i--) {
						if (slist[i].id) {
							gengSubs.push({
								id: slist[i].id,
								guestid: ginfo.id,
								subjectid: slist[i].subjectid,
								num: slist[i].cardtype?0:slist[i].nownum,
								nownum: slist[i].cardtype?0:slist[i].nownum,
								price: slist[i].price,
								discount: slist[i].cardtype?0:slist[i].disprice/slist[i].price,
								disprice: slist[i].cardtype?0:slist[i].disprice,
								amount: slist[i].cardtype?0:slist[i].disprice*slist[i].nownum,
								cardid: 0,
								cardtype: slist[i].cardtype?1:2,
								addtime: addtime,
								endtime: slist[i].cardtype?Math.round(new Date(slist[i].endtime).valueOf()/1000):0,
								shopid: shopid,
							})
						} else {
							addSubs.push({
								guestid: ginfo.id,
								subjectid: slist[i].subjectid,
								num: slist[i].cardtype?0:slist[i].nownum,
								nownum: slist[i].cardtype?0:slist[i].nownum,
								price: slist[i].price,
								discount: slist[i].cardtype?0:slist[i].disprice/slist[i].price,
								disprice: slist[i].cardtype?0:slist[i].disprice,
								amount: slist[i].cardtype?0:slist[i].disprice*slist[i].nownum,
								cardid: 0,
								cardtype: slist[i].cardtype?1:2,
								addtime: addtime,
								endtime: slist[i].cardtype?Math.round(new Date(slist[i].endtime).valueOf()/1000):0,
								shopid: shopid,
							})
						}
					}

					if (gengSubs.length) {
						let subsGengRes = await this.model('or_shop_guestcardsubject').db(model.db()).updateMany(gengSubs);
						if (!subsGengRes) {
							await model.rollback();
							return this.fail('更新项目失败');
						}
					}

					if (addSubs.length) {
						let subsAddRes = await this.model('or_shop_guestcardsubject').db(model.db()).addMany(addSubs);
						if (!subsAddRes) {
							await model.rollback();
							return this.fail('添加项目失败');
						}
					}
				}

				if (glist.length) {
					let gengGods = [], addGods = [];
					for (var i = glist.length - 1; i >= 0; i--) {
						if (glist[i].id) {
							gengGods.push({
								id: glist[i].id,
								num: glist[i].nownum,
								nownum: glist[i].nownum,
								disprice: glist[i].isgift?0:glist[i].disprice,
								amount: glist[i].isgift?0:glist[i].disprice*glist[i].nownum,
								shopid: shopid,
								addtime: addtime,
								isgift: glist[i].isgift?1:0,
								brandid: glist[i].brandid,
							})
						} else {
							addGods.push({
								guestid: ginfo.id,
								goodsid: glist[i].goodsid,
								price: glist[i].price,
								num: glist[i].nownum,
								nownum: glist[i].nownum,
								disprice: glist[i].isgift?0:glist[i].disprice,
								amount: glist[i].isgift?0:glist[i].disprice*glist[i].nownum,
								shopid: shopid,
								addtime: addtime,
								isgift: glist[i].isgift?1:0,
								brandid: glist[i].brandid,
							})
						}
					}

					if (gengGods.length) {
						let godsGengRes = await this.model('or_shop_guest_temp_reserve').db(model.db()).updateMany(gengGods);
						if (!godsGengRes) {
							await model.rollback();
							return this.fail('更新产品失败');
						}
					}

					if (addGods.length) {
						let godsAddRes = await this.model('or_shop_guest_temp_reserve').db(model.db()).addMany(addGods);
						if (!godsAddRes) {
							await model.rollback();
							return this.fail('添加产品失败');
						}
					}
				}

				let gengGuset = await model.where({id: ginfo.id}).update({balance: ginfo.balance, giftbalance: ginfo.giftbalance, level: ginfo.level});

				if (!gengGuset) {
					await model.rollback();
					return this.fail('更新客户余额等信息失败');
				}

				await model.commit();
				return this.success('编辑起初成功');
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('编辑初始失败');
			}
		})
	}

	// 审核客户起初信息
	async checkfinshinitialAction(){
		let id = this.post('id');

		let initial = await this.model('or_guest').where({id:id}).find();

		if (initial.initial_info) {
			return this.fail('当前客户起初已审核！');
		}

		let res = await this.model('or_guest').where({id:id}).update({initial_info: 1});
		return res?this.success('起初审核成功'):this.fail('起初审核失败');
	}

	// 生成卡号
	async getcardsn(cardid ,db){
		let dinfo = await this.model('or_department').db(db).where({id:this.shop_userinfo.departmentid}).find();
		let cinfo = await this.model('or_card').db(db).where({id:cardid}).find();
		let nums = cinfo.nums+1;
		await this.model('or_card').where({id:cardid}).db(db).update({nums:nums});
		let cardnum = dinfo.orcode+''+cardid+''+nums;
		return cardnum;
	}

	// 获取客户账户记录、订单记录、卡项记录、暂存记录
	async getguestlogAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let gid = page.guestid;
		let type = page.type;

		let list = {};
		if (type==='1') {
			list = await this.model('or_shop_guest_accountlog')
						.alias('ga')
						.field('ga.*,a.order_sn, s.order_sn as ordername')
						.join('`think_or_shop_order` a on a.id=ga.orderid')
						.join('`think_or_shop_backcardorder` s on s.id=ga.orderid')
						.where({'ga.guestid': gid})
						.page(pages, limits)
						.order('id DESC')
						.countSelect();
		} else if (type==='2') {
			list = await this.model('or_shop_order').where({guestid: gid}).page(pages, limits).order('id DESC').countSelect();
		} else if (type==='3') {
			list = await this.model('or_shop_guestcardlog')
						.alias('gl')
						.field('gl.*, IFNULL(c.name,"无") as cardname, cs.cardtype, s.name as subjectname, cs.price')
						.join('`think_or_shop_order` o on gl.orderid=o.id')
						.join('`think_or_shop_card` c on c.id=gl.guestcardid')
						.join('`think_or_shop_guestcardsubject` cs on cs.id=gl.guestcardinfoid')
						.join('`think_or_subject` s on s.id=cs.subjectid')
						.where({'o.guestid': gid, 'o.ordertype': 2})
						.page(pages, limits)
						.order('gl.id DESC')
						.countSelect();
		} else if (type==='4') {
			list = await this.model('or_shop_orderinfo')
						.alias('oi')
						.field('oi.*, o.addtime, b.name as bname, o.status')
						.join('`think_or_shop_order` o on o.id=oi.orderid')
						.join('`think_or_brand` b on b.id=oi.brandid')
						.where({'o.guestid': gid, 'oi.consumetype': 3,'o.status': ['!=', 0]})
						.page(pages, limits)
						.order('oi.id DESC')
						.countSelect();
		}
		return this.json(list);
	}

	// 获取机构会员卡列表
	async getlevelsAction(){
		let shopid = this.shop_userinfo.departmentid;

		let orid = await this.model('or_department').where({id: shopid}).getField('pid',true);

		let data = await this.model('or_guest_vipgrade').where('departmentid='+orid+' or departmentid=0').order('vipgrade ASC').select();

		return this.json(data);
	}

	async queryginfoAction(){
		let gid = this.post('id');

		let currentTime = Math.round(new Date().valueOf()/1000);

		let shopid = this.shop_userinfo.departmentid;
		// 需要获取的信息
		// 客户的基本信息
		let ginfo = await this.model('or_guest')
				.alias('g')
				.field('g.*, v.vipname')
				.join('`think_or_guest_vipgrade` v on v.id=g.level')
				.where({'g.id': gid})
				.find();

		// 客户的项目信息
		let slist = await this.model('or_shop_guestcardsubject')
				.alias('gs')
				.field('gs.*, s.name as sname')
				.join('`think_or_subject` s on s.id=gs.subjectid')
				.where('gs.shopid='+shopid+' AND gs.guestid='+gid+' AND (gs.endtime>'+currentTime+' OR gs.nownum>0) AND gs.isdisabled=0')
				.select();

		// 客户的产品信息
		let glist = await this.model('or_shop_guest_temp_reserve')
				.alias('t')
				.field('t.*, g.name as gname')
				.join('`think_or_goods` g on g.id=t.goodsid')
				.where('t.guestid='+gid+' AND t.shopid='+shopid+' AND t.nownum > 0 AND t.isdisabled=0')
				.select();

		let data = {
			ginfo: ginfo,
			slist: slist,
			glist: glist
		}

		return this.json(data);
	}

	async guestAction(){
		let gid = this.get('gid');
		let data = await this.model('or_guest')
				.alias('g')
				.field('g.*,v.vipname, v.goodsdiscount, v.subjectdiscount')
				.join('`think_or_guest_vipgrade` v on v.id=g.level')
				.where({'g.id': gid})
				.find();
		return this.json(data);
	}

	// 重置客户密码为当前手机号
	async resetpasswordAction(){
		let gid = this.get('gid');

		let ginfo = await this.model('or_guest').where({id: gid}).find();

		let phone = ginfo.phone;

		ginfo.username = phone;
		ginfo.password = think.md5(phone);

		let resetInfo = await this.model('or_guest').where({id: gid}).update(ginfo);

		return resetInfo?this.success('重置密码成功'):this.fail('重置密码失败');
	}


	// 获取客户的相关服务人员
	async getGuestServiceManAction () {
		let id = this.get('id')
		let list = await this.model('or_allotuser').alias('a').field('u.*').join('left join `think_or_app_user` u on a.uid = u.id').where({'a.gid': id}).select()
		return this.json(list)
	}

}